package com.hourses.filter;

import com.alibaba.fastjson2.JSON;
import com.hourses.pojo.Result;
import com.hourses.utils.WarehouseConstants;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description:
 * @Author:LiTao
 * @Date:2025/4/27 17:07
 */
public class LoginCheckFilter implements Filter {
    private StringRedisTemplate redisTemplate;
    public void setRedisTemplate(StringRedisTemplate redisTemplate){
        this.redisTemplate = redisTemplate;
    }
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        //白名单，允许通过的url
        List<String> passUrl = new ArrayList<>();
        passUrl.add("/captcha/captchaImage");
        passUrl.add("/login");
        passUrl.add("/logout");
        passUrl.add("/product/img-upload");

        //过滤器拦截到的当前请求的url接口
        String url = request.getServletPath();

        //1.判断是否是白名单当中的url
        if (passUrl.contains(url)||url.contains("/img/upload")){
            //是的话就放行
            filterChain.doFilter(request,response);
            return;
        }

        //2.如果不是白名单当中的url，判断有没有登录
        String token = request.getHeader(WarehouseConstants.HEADER_TOKEN_NAME);
        if (StringUtils.hasText(token)&&redisTemplate.hasKey(token)){
            //请求头有token并且token在缓存中，也放行
            filterChain.doFilter(request,response);
            return;
        }

        //除了以上两种情况以外，都不放行
        Result err = Result.err(Result.CODE_ERR_UNLOGINED, "尚未登陆！");
        String reStr = JSON.toJSONString(err);
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.print(reStr);
        out.flush();
        out.close();
    }
}
